<?php
namespace Mobile\Controller;
use Think\Controller;

class SellerController extends Controller{
    
    private $www_url;   //域名
    
    public function _initialize(){
        $this->www_url = C('WWW_ROOT');
    }
    
    /**
     * 申请模特肖像权【待完善，续费？？】
     * @param type $month       申请肖像权时间（月）
     * @param type $money       申请肖像权的总费用
     * @param type $begin_date  申请肖像权开始时间，暂时定为当前时间，不用管
     * @param type $uid         卖家id
     * @param type $mid         模特id
     * @return 1：成功；0：失败；
     */
    public function applyForPortrait($month=1, $money=300, $begin_date='', $uid=0, $mid=0){
        $begin_date = $begin_date==''?NOW_TIME:  strtotime($begin_date);
        $end_date = mktime(date('H',$begin_date), date('i', $begin_date), date('s', $begin_date), 
                date('n', $begin_date)+$month, date('j', $begin_date), date('Y', $begin_date));
        
        $data = array(
            'sid'             => $uid,
            'mid'             => $mid,
            'money_per_month' => $money/$month,
            'month_count'     => $month,
            'total_money'     => $money,
            'begin_date'      => $begin_date,
            'end_date'        => $end_date,
            'status'          => 1,
        );
        if(M('Apply_portrait')->add($data)){
            $this->sendMsg($mid, 1, '卖家申请了您的肖像权');
            $this->returnAjax(1, '申请肖像权创建成功，等待模特确认');
        }
        $this->returnAjax(0, '申请肖像权创建失败，请联系管理员');
    }
    /**
     * 邀请体验
     * @param type $uid         卖家id
     * @param type $mid         模特id
     * @param type $title       标题
     * @param type $total_fee   交易金额
     * @param type $product_num 体验品数量
     * @param type $end_date    截止时间
     * @param type $product_url 体验品url
     * @param type $return_type 返还类型：0-返回；1-折价；2-赠送
     * @param type $value       体验品价格
     * @param type $remark      商家备注
     */
    public function inviteExperience($uid=0, $mid=0, $title='', $total_fee=0, $product_num=1, $end_date=0, $product_url='', $return_type=0, $value=0, $remark=''){
        $data = array(
            'sid'         => $uid,
            'mid'         => $mid,
            'title'       => urldecode($title),
            'total_fee'   => $total_fee,
            'product_num' => $product_num,
            'product_url' => $product_url,
            'end_time'    => strtotime($end_date),
            'update_time' => NOW_TIME,
            'return_type' => $return_type,
            'value'       => $value,
            'remark'      => urldecode($remark),
            'status'      => 1,
        );
        if(M('Invite_experience')->add($data)){
            $this->sendMsg($mid, 2, '卖家邀请您体验产品');
            $this->returnAjax(1, '邀请体验成功，静候模特回复');
        }
        $this->returnAjax(0, '邀请体验失败，请稍后重试');
    }
    
    public function getApplyModels($uid, $p, $per_page) {
        $model = M();
        //卖家申请过肖像权的模特的微博列表
        $data_query = 'SELECT * FROM md_weibo WHERE uid in (SELECT DISTINCT md_user.id FROM md_apply_portrait JOIN md_user'
                . ' ON md_apply_portrait.mid=md_user.id WHERE sid=' .$uid. ' and md_apply_portrait.status>4) '
                . 'AND `status`=1 ORDER BY add_time DESC LIMIT ' .($p-1)*$per_page. ',' .$per_page. ';';
        $data = $model->query($data_query);
        //总的条目数
        $count_query = 'SELECT COUNT(id) as count FROM md_weibo WHERE uid in (SELECT DISTINCT md_user.id FROM md_apply_portrait JOIN md_user'
                . ' ON md_apply_portrait.mid=md_user.id WHERE md_apply_portrait.sid=' .$uid. ') AND `status`=1;';
        $count = $model->query($count_query);
        $count = $count[0]['count'];
        
        if($count > 0){
            foreach ($data as $key => $value){
                $user_info = M('User')->field('nickname, avatar_url')->find($value['uid']);
                $user_info['avatar_url'] = $this->www_url . $user_info['avatar_url'];
                $data[$key] = array_merge($data[$key], $user_info);

                $data[$key]['add_time'] = date('Y-m-d', $value['add_time']);

                $pics = M('Weibo_pic')->field('pic_url')->where(array('w_id' => $value['id']))->select();
                foreach ($pics as $k => $v){
                    $pics[$k] = $this->www_url . $v['pic_url'];
                }
                $data[$key]['pic'] = $pics;
            }
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '获取申请过的模麻豆表成功',
                'data'  => $data,
                'total_count' => $count,
            ));
        }
        $this->returnAjax(0, '还未申请过麻豆肖像权');
    }
  
    /**
    * 获取卖家邀请过的麻豆体验列表
    * @param type $uid 卖家id
    * @param type $per_page 分页，单页条目数
    */
    public function getInviteModels($uid=0, $per_page=3) {
        //卖家邀请体验列表
        $page_data = page('Invite_experience', $per_page, array('sid' => $uid, 'md_invite_experience.status' => array('gt', 5)), 
                array('update_time' => 'desc'), 'md_user on md_invite_experience.mid=md_user.id', 
                'md_user.id AS mid, md_invite_experience.id AS eid, avatar_url, nickname, return_type, '
                . 'value, md_invite_experience.status, update_time, experience');
        $data = $page_data['list'];
        
        if(!empty($data)){
            foreach ($data as $key => $value){
                $pics = M('Experience_pics')->field('pic_url')->where(array('invite_id' => $value['eid']))->select();
                foreach ($pics as $k => $v){
                    $pics[$k] = $this->www_url . $v['pic_url'];
                }
                $data[$key]['pic'] = $pics;
                $data[$key]['update_time'] = date('Y-m-d', $value['update_time']);;
                $data[$key]['avatar_url'] = $this->www_url . $value['avatar_url'];
            }
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '获取邀请麻豆列表成功',
                'data'  => $data,
                'total_count' => $page_data['total'],
            ));
        }
        $this->returnAjax(0, '还未邀请过麻豆');
    }
    
    /**
     * 获取个人主页上部分个人信息
     * @param type $uid 用户id
     * @return 用户头像，昵称，评价数，关注数，粉丝数
     */
    public function getPersonalInfo($uid=0){
        $seller = M('User')->field('nickname, avatar_url, cover_img')->where(array('status' => 1, 'id' => $uid))->find();
        $c1 = M('Invite_experience')->where(array('sid' => $uid, 'status' => array('gt', 6)))->count();
        $c2 = M('Apply_portrait')->where(array('sid' => $uid, 'status' => array('gt', 6)))->count();
        $comment_num = $c1 + $c2;
        $attention_num = M('Follow')->where(array('uid' => $uid, 'status' => 1))->count();
        $fans_num = M('Follow')->where(array('pid' => $uid, 'status' => 1))->count();
        if(!empty($seller)){
            $seller['avatar_url'] = $this->www_url . $seller['avatar_url'];
            $seller['cover_img'] = $this->www_url . $seller['cover_img'];
            $seller['comment_num'] = $comment_num;
            $seller['attention_num'] = $attention_num;
            $seller['fans_num'] = $fans_num;
            $this->returnAjax(1, '获取用户部分信息成功', $seller);
        }
        $this->returnAjax(0, '获取用户部分信息失败');
    }

    /**
     * 获取邀请体验评论列表
     * @param type $uid     用户id
     * @param type $per_page
     */
    public function getCommentExperienceList($uid=0, $per_page=3){
        $page_data = page('Invite_experience', $per_page, array('sid' => $uid), 
                array('update_time' => 'desc'), 'md_user on md_invite_experience.mid=md_user.id', 
                'md_user.id AS mid, md_invite_experience.id AS eid, avatar_url, nickname, total_fee, update_time, product_num');
        $data = $page_data['list'];
        if(!empty($data)){
            foreach ($data as $key => $value){
                $data[$key]['avatar_url'] = $this->www_url . $value['avatar_url'];
                $data[$key]['update_time'] = date('Y-m-d', $value['update_time']);
            }
            $this->returnAjax(1, '获取邀请体验评论列表成功', $data);
        }
        $this->returnAjax(0, '不存在邀请体验评论');
    }
    
    /**
     * 获取申请肖像权评论列表
     * @param type $uid     用户id
     * @param type $per_page
     */
    public function getCommentApplyList($uid=0, $per_page=3){
        $page_data = page('Apply_portrait', $per_page, array('sid' => $uid), 
                array('begin_date' => 'desc'), 'md_user on md_apply_portrait.mid=md_user.id', 
                'md_user.id AS mid, md_apply_portrait.id AS aid, avatar_url, nickname, total_money, begin_date, end_date');
        $data = $page_data['list'];
        if(!empty($data)){
            foreach ($data as $key => $value){
                $data[$key]['avatar_url'] = $this->www_url . $value['avatar_url'];
                $data[$key]['begin_date'] = date('Y-m-d', $value['begin_date']);
                $data[$key]['end_date'] = date('Y-m-d', $value['end_date']);
            }
            $this->returnAjax(1, '获取申请肖像权评论列表成功', $data);
        }
        $this->returnAjax(0, '不存在申请肖像权评论');
    }

    /**
     * 获取商户编辑信息
     * @param type $uid 商户id
     */
    public function getUserInfo($uid=0){
        $user = M('User')->field('nickname, avatar_url')->find($uid);
        $user['avatar_url'] = $this->www_url . $user['avatar_url'];
        
        $seller = M('User_seller')->field('shop_name, shop_url, user_group, brand_lure, alipay_account, wechat')->where(array('uid' => $uid))->find();
        //获取配置信息集合
        $tmp = get_array_configs(array('style', 'user_group'));
        //处理得到店铺标签
        $style = explode(',', $seller['brand_lure']);
        $config = $tmp['style'];
        foreach ($style as $k => $v){
            $styles[] = array('id' => $v, 'name' => $config[$v]);
        }
        $seller['brand_lure'] = $styles;
        //得到用户群
        $groups = $tmp['user_group'];
        $seller['user_group'] = array('id' => $seller['user_group'], 'name' => $groups[$seller['user_group']]);
        //数据合并
        $data = array_merge($user, $seller);
        $this->returnAjax(1, '获取成功', $data);
    }
    
    /**
     * 编辑保存个人信息
     * @param type $uid             卖家id
     * @param type $nickname        卖家昵称
     * @param type $shop_name       店铺名称
     * @param type $shop_url        店铺url
     * @param type $brand_lure      店铺标签
     * @param type $user_group      用户群
     * @param type $alipay_account  支付宝账户
     */
    public function editUserInfo($uid=0, $nickname='', $shop_name='', $shop_url='', 
            $brand_lure='0', $user_group=0, $alipay_account='', $wechat=''){
        
        if(empty($uid)){
            $this->returnAjax(0, '用户id为空');
        }
        $isok = M('User')->save(array('id' => $uid, 'nickname' => $nickname));
        $data = array(
            'shop_name'      => $shop_name,
            'shop_url'       => $shop_url,
            'brand_lure'     => $brand_lure,
            'user_group'     => $user_group,
            'alipay_account' => $alipay_account,
            'wechat'         => $wechat,
        );
        if(M('User_seller')->where(array('uid' => $uid))->save($data)){
            $this->returnAjax(1, '个人信息修改成功');
        }
        $this->returnAjax(0, '个人信息保存失败');
    }
    

    




















/*************************** 公共应用函数 *******************************/
    /**
     * ajaxReturn 返回函数重写
     * @param type $code    code
     * @param type $msg     msg
     * @param type $data    data
     */
    public function returnAjax($code, $msg, $data=''){
        $this->ajaxReturn(array(
            'code'  => $code,
            'msg'   => $msg,
            'data'  => $data,
        ));
    }
    
    /**
     * 通过融云发送提醒消息
     * @param type $uid     被发送用户id，多个用户id用,分开
     * @param type $order   消息类型：1申请肖像权；2邀请体验
     * @param type $msg     消息内容：暂为空
     */
    public function sendMsg($uid=0, $order=1, $msg=''){
        vendor('Api.ServerAPI');
        $p = new \ServerAPI(C('appKey'), C('appSecret'));
        $content = '{"content":"' .$msg. '","extra":"order_'.$order.'"}';
        $to = array($uid);
        $msg = $p->messageSystemPublish(2, $to, 'RC:TxtMsg', $content);
    }
}